<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/15
 * Time: 15:52
 */

namespace app\common\mysic\dividend;

use app\common\library\wechat\Abonus;
use app\common\mysic\MysicBase;
use app\common\mysic\order\OrderOpInterface;
use app\common\mysic\order\SystemDividendOrderOp;
use app\mocks\extend\MockWeChatProfitSharing;


class SystemDividendHandler extends MysicBase implements DividendHandlerInterface
{
    /**
     * @var Abonus|MockWeChatProfitSharing

     */
    protected $dividendApi;
    /**
     * @var SystemDividendOrderOp
     */
    protected $orderOp;


    public function setDividendApi($api)

    {
        $this->dividendApi = $api;
        return $this;
    }

    public function setOp(OrderOpInterface $op)
    {
        $this->orderOp = $op;
        return $this;
    }

    protected function addReceiver()
    {
        return $this->dividendApi->receiverAdd();
    }

    public function dividendApply()
    {
        return $this->dividendApi->dividendApply();
    }

    public function dividendQuery()
    {
        $ret = $this->dividendApi->dividendApplyQuery();
        if(!$ret) {
            sleep(5);
            $ret = $this->dividendQuery();
            if($ret) {
                return true;
            }
        }
        return true;
    }

    public function dividendOver($description = '分账已完结')
    {
        return $this->dividendApi->setUserOrder($this->orderOp->getOrder())->dividendOver($description);
    }


    public function doDividend($needAddReceiver = true)
    {
        try{
            $this->dividendApi->setUserOrder($this->orderOp->getOrder())->setDividendOrder($this->orderOp->getModel());
            if($needAddReceiver) {
                $ret = $this->addReceiver();
                if(!$ret) {
                    $this->log->error('失败', '添加分账人');
                    return false;
                }
            }

            $ret = $this->dividendApply();
            if (!$ret) {
                $this->log->error('失败', '提交分账申请');
                return false;
            }
            $ret = $this->dividendQuery();
            if (!$ret) {
                $this->log->error('失败', '分账查询结果');
                return false;
            }
        }catch(\Exception $e) {
            $this->log->error(exceptionLogFormat($e), '调用分账接口抛出异常');//todo 当分账返回失败时，根据返回的err_code，处理失败的分账订单
            return false;
        }
        return true;
    }

}